package com.apes.hr.base.service;

import com.alibaba.fastjson.JSON;
import com.apes.framework.api.DomainService;
import com.apes.framework.jpa.generator.service.SequenceService;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.jpa.spec.model.Filter;
import com.apes.framework.jpa.spec.model.Group;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.hr.base.model.Job;
import com.apes.hr.base.repository.JobRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 功能：职位
 *
 * @author HuJianLin
 * @create 2018-04-28 14:35
 */
@Service("hrJobService")
public class JobService extends DomainService {
    @Autowired
    public JobRepository jobRepository;
    @Autowired
    public SequenceService sequenceService;

    public Job save(SimpleRequest request) {
        Job job = request.getO(Job.class);
        return jobRepository.saveAndFlush(job);
    }


    /**
     * 功能：下拉模糊查询使用
     * @param request
     * @return
     */
    public Page<Job> find(SimpleRequest request) {
        return jobRepository.find( request.get("key"), PageRequest.of(request.get("page"), request.get("size")) );
    }

    public Page<Job> findAll(SimpleRequest request) {
        List<Map> filters = request.get("condition");
        Sort sort = new Sort(Sort.Direction.DESC, "id");
        return jobRepository.findAll(JpaDsl.toCriteria(filters), PageRequest.of(request.get("page"), request.get("size"), sort));
    }

    public Job findOne(String id) {
        return jobRepository.findOne(id);
    }

    public Page<Job> findByIdOrName(SimpleRequest request) {
        List<Filter> filters = JSON.parseArray(request.getJO().getJSONObject("group").getJSONArray("filters").toString(), Filter.class);
        Sort sort = new Sort(Sort.Direction.DESC, "id");
        Group group = new Group();
        group.setOperator("or");
        group.setFilters(filters);
        return jobRepository.findAll(
                group.build(false),
                PageRequest.of(request.get("page"), request.get("size"), sort));
    }
}
